import { Component } from '@angular/core';
import { NavController, Platform, NavParams } from 'ionic-angular';
import { RestService } from '../../app/services/rest.service';
import { TranslateService } from '@ngx-translate/core';
import { AlarmRecPage } from '../alarmRec/alarmRec';

import * as _ from 'lodash';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  refreshInterval = 3000;
  refreshTask: any;

  moveTotal = '-';
  heart = '-';
  breathe = '-';

  pressureH = '-';
  pressureL = '-';

  SHALLOW_SLEEP_MODE = "1";
  DEEP_SLEEP_MODE = "2";
  deepSleep = 0;
  shallowSleep = 0;
  totalSleep = 0;
  sleepScore = 0;
  sleepAdjustment = '';
  sleepDisplay: any;

  institution: any;
  personAway: any = '-';
  platform: any;
  url = 'data/device';
  user: any;
  persons: any[];
  public person: any;
  deviceId; any;
  id: any;
  personId = null;
  total: number;
  mute = false;
  playAudio = false;
  onSuccess: any;
  onError: any;
  constructor(private rest: RestService,
    platform: Platform,
    private translate: TranslateService,
    public navParams: NavParams,
    public navCtrl: NavController) {
    this.platform = platform;
    this.person = navParams.data;
    this.personId = navParams.data.personId;
  }

  ionViewCanEnter(): boolean {
    return true;
  }

  ionViewDidEnter() {
    this.refresh();
    this.refreshTask = setInterval(() => {
      this.refresh();
    }, this.refreshInterval);
  }

  ionViewWillLeave() {
    if (this.refreshTask) {
      clearInterval(this.refreshTask);
    }
  }

  getUpAlarm(person) {
    if (person) {
      return person.upAlarm && person.upAlarmFlag;
    } else {
      return '';
    }
  }

  getSideAlarm(person) {
    if (person) {
      return person.sideAlarm && person.sideAlarmFlag;
    } else {
      return '';
    }
  }

  getAwayAlarm(person) {
    if (person) {
      return person.awayAlarm && person.awayAlarmFlag;
    } else {
      return '';
    }
  }

  getUpAlarmFlag(person) {
    if (person) {
      return !person.upAlarm && person.upAlarmFlag;
    } else {
      return '';
    }
  }

  getSideAlarmFlag(person) {
    if (person) {
      return !person.sideAlarm && person.sideAlarmFlag;
    } else {
      return '';
    }
  }

  getAwayAlarmFlag(person) {
    if (person) {
      return !person.awayAlarm && person.awayAlarmFlag;
    } else {
      return '';
    }
  }

  getTurnOverReminderString(person) {
    if (person.turnOverReminderAlarmFlag) {
      return this.translate.get('TURN_OVER')['value'];}
    }

  getBedAlarmString(person) {
    if (person.upAlarmFlag) {
      return this.translate.get('UP')['value'];
    } else if (person.sideAlarmFlag) {
      return this.translate.get('SIDE')['value'];
    } else if (person.awayAlarmFlag) {
      return this.translate.get('AWAY')['value'];
    } else if (person.deviceAlarmFlag) {
      return this.translate.get('offline')['value'];
    } else {
      return this.translate.get('normal')['value'];
    }
  }

  getHeartAlarm(person) {
    if (person.heartAlarmFlag) {
      return person.heartAlarmFlag;
    }
  }

  getBreatheAlarm(person) {
    if (person.breatheAlarmFlag) {
      return person.breatheAlarmFlag;
    }
  }

  getBedColor() {
    return "background-color: red;";
  }

  getMove(person) {
    if (person) {
      return person.move;
    } else {
      return '';
    }
  }

  getName(person) {
    if (person) {
      return person.personName;
    } else {
      return '';
    }
  }

  getWetAlarm(person) {
    if (person) {
      return person.wetAlarmFlag;
    } else {
      return '';
    }
  }

  getWetString(person) {
    if (this.getWetAlarm(person)) {
      return this.translate.get('WET')['value'];
    }
    else {
      return this.translate.get('dry')['value'];
    }
  }

  getRingAlarm(person) {
    if (person) {
      return person.ringAlarmFlag;
    } else {
      return '';
    }
  }

  getRingAlarmString(person) {
    if (this.getRingAlarm(person)) {
      return this.translate.get('RING')['value'];
    }
  }

  refresh() {
    this.rest.get('/data/person/' + this.person.id).subscribe(data => {
      this.person = data;
    });

    this.rest.get('/api/influx/getHeartByPersonId?personId=' + this.person.id).subscribe(pdata => {
     // console.log(pdata);
     // this.person.heart = "--";
     // this.person.hearttime = "-----";
      this.pressureH = "-";
      this.pressureL = "-";
      if(pdata!=null){
       // this.heart = pdata[2];
        //var date = new Date(pdata[0]).toLocaleString();
        //this.person.hearttime = this.dateformat(pdata[0]);
        this.pressureH = pdata[3];
        this.pressureL = pdata[4];
      }

    },message=>{
      console.error('Failed to get Coordinate By PersonId in: ' + message);
    });

    this.rest.getWithParams('/api/pro/allAlarmCounters', {
      personId: this.person.id,
      interval: this.getSecondsFromLast8Am()
    }).subscribe(resp => {
      this.moveTotal = resp['move'];
    });

    this.rest.getWithParams('/api/pro/realTimeData', {
      personId: this.person.id
    }).subscribe(data => {
      this.breathe = data['breathe'];
      this.heart = data['heart'];
    });

    // sleep, 5s for one data point
    const sleepIntervals = this.getSleepIntervals();
    const sleepStep = 5;
    this.rest.getWithParams('/api/pro/counterRange', {
      counter: 'sleep',
      personId: this.person.id,
      startTime: sleepIntervals[0],
      endTime: sleepIntervals[1],
      step: sleepStep
    }).subscribe(resp => {
      if (!resp || !_.isArray(resp) || resp.length < 1) {
        this.deepSleep = 0;
        this.shallowSleep = 0;
        return;
      }

      this.deepSleep = 0;
      this.shallowSleep = 0;
      const data = resp;
      data.forEach(item => {
        if (item[1] === this.DEEP_SLEEP_MODE) {
          this.deepSleep++;
        } else if (item[1] === this.SHALLOW_SLEEP_MODE) {
          this.shallowSleep++;
        }
      });
      this.deepSleep = Math.round(this.deepSleep * 100 * sleepStep / 3600.0) / 100.0;
      this.shallowSleep = Math.round(this.shallowSleep * 100 * sleepStep / 3600.0) / 100.0;
      this.totalSleep = Math.round((this.deepSleep + this.shallowSleep) * 100) / 100.0;
      this.sleepCalculation();
    });

    if ((this.getAwayAlarm(this.person) || this.getUpAlarm(this.person) || this.getSideAlarm(this.person) || this.getTurnOverReminderString(this.person)
      || this.getHeartAlarm(this.person) || this.getBreatheAlarm(this.person) || this.getWetAlarm(this.person) || this.getRingAlarm(this.person)) && !this.mute) {
        this.playAudio = true;
        // if (this.platform.is('cordova')){
          //   this.vibration.vibrate(1000);
          //   this.nativeAudio.play('uniqueId1').then(this.onSuccess, this.onError);
          // }
        } else {
          this.playAudio = false;
    }
  }

  sleepCalculation() {
    const total = this.deepSleep + this.shallowSleep;
    if (this.deepSleep <= 0.1) {
      // If deep sleep is less than 6 minutes (0.1 hours), treat it as bad data
      this.sleepScore = 0;
    } else {
      const ratio = (this.deepSleep * 100.0) / total;
      if (ratio < 12.5) {
        this.sleepScore = 0;
      } else if (ratio >= 12.5 && ratio < 20) {
        this.sleepScore = Math.round(50 + ((80 - 50) / (20.0 - 12.5)) * (ratio - 12.5));
      } else if (ratio >= 20 && ratio < 22) {
        this.sleepScore = Math.round(80 + ((90 - 80) / (22.0 - 20.0)) * (ratio - 20.0));
      } else if (ratio >= 22 && ratio < 23) {
        this.sleepScore = Math.round(90 + ((95 - 90) / (23.0 - 22.0)) * (ratio - 22.0));
      } else if (ratio >= 23 && ratio < 25) {
        this.sleepScore = Math.round(95 + ((100 - 95) / (25.0 - 23.0)) * (ratio - 23.0));
      } else if (ratio >= 25) {
        this.sleepScore = 100;
      }
    }

    this.sleepDisplay = this.sleepScore;
    if (this.sleepScore >= 100) {
      this.sleepAdjustment = 'sleepPerfect';
    } else if (this.sleepScore >= 95) {
      this.sleepAdjustment = 'sleepGood';
    } else if (this.sleepScore >= 85) {
      this.sleepAdjustment = 'sleepNormal';
    } else if (this.sleepScore >= 70) {
      this.sleepAdjustment = 'sleepFair';
    } else if (this.sleepScore >= 60) {
      this.sleepAdjustment = 'sleepPass';
    } else {
      this.sleepAdjustment = 'sleepBelow';
      this.sleepDisplay = '< 50';
    }
  }

  getSleepColor() {
    if (this.sleepScore >= 100) {
      return 'secondary';
    } else if (this.sleepScore >= 95) {
      return 'secondary';
    } else if (this.sleepScore >= 85) {
      return 'primary';
    } else if (this.sleepScore >= 70) {
      return 'primary';
    } else if (this.sleepScore >= 60) {
      return 'primary';
    } else {
      return 'danger';
    }
  }

  getSecondsFromLast8Am() {
    let hour = new Date().getHours();
    hour = hour >= 8 ? (hour - 8) : (24 + hour - 8);
    return hour * 60 * 60 + new Date().getMinutes() * 60 + new Date().getSeconds() - 1;
  }

  getSleepIntervals() {
    const times = [];
    let hour = new Date().getHours();
    const currentTime = Math.round(new Date().getTime() / 1000);
    if (hour >= 20) {
      const pastSecondsFrom8Pm = (hour - 20) * 60 * 60 + new Date().getMinutes() * 60 + new Date().getSeconds();
      const endTime = currentTime;
      const startTime = endTime - pastSecondsFrom8Pm;
      times.push(startTime);
      times.push(endTime);
      return times;
    } else if (hour < 20 && hour >= 8) {
      const endTime = currentTime - this.getSecondsFromLast8Am();
      const startTime = endTime - 12 * 60 * 60;
      times.push(startTime);
      times.push(endTime);
      return times;
    } else if (hour < 8) {
      const pastSecondsFrom8Pm = (hour + 4) * 60 * 60 + new Date().getMinutes() * 60 + new Date().getSeconds();
      const endTime = currentTime;
      const startTime = endTime - pastSecondsFrom8Pm;
      times.push(startTime);
      times.push(endTime);
      return times;
    }
  }

  toggleMute() {
    this.mute = !this.mute;
  }

  nav2alarmRec(alarm) {
    this.navCtrl.push(AlarmRecPage, {
      person: this.person,
      alarm: alarm
    });
  }
}
